/*
* @(#)MaintDmsConvertToCompoundDocAction.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.io.InputStream;
import java.net.URLConnection;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsContent;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsValidation;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DmsContentManager;
import com.dcivision.dms.core.DmsContentStoreHandler;
import com.dcivision.dms.core.DmsDocumentNameConvertor;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.DocumentValidateManager;
import com.dcivision.dms.dao.DmsContentDAObject;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;

/**
  MaintDmsConvertToCompoundDocAction.java

  This class is for maint dms dmsDocument action

    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   08/11/2004
    @version         $Revision: 1.12.2.3 $
 */

public class MaintDmsConvertToCompoundDocAction extends MaintDmsDocumentAction {

  public static final String REVISION = "$Revision: 1.12.2.3 $";
  
  protected static final String MESSAGE_CONVERT_SUCCESS="dms.message.convert_success";

  public MaintDmsConvertToCompoundDocAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.dms.dao.DmsDocumentDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.DMS_PUBLIC_FOLDER);
  }
  
  /**
   * execute - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintDmsDocumentForm actionForm=(MaintDmsDocumentForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    // Set function code if necessary.
    if (!Utility.isEmpty(actionForm.getCurFunctionCode())) {
      this.setFunctionCode(actionForm.getCurFunctionCode());
    }else if(!Utility.isEmpty(request.getParameter("sCurFunctionCode"))){
      this.setFunctionCode(request.getParameter("sCurFunctionCode"));
    }
    if( !Utility.isEmpty(functionCode)) {
      request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY,functionCode);
    } else {
      request.setAttribute(GlobalConstant.FUNCTION_CODE_KEY,this.getFunctionCode());
    }
    
    String opMode = actionForm.getOpMode();
    String navMode = actionForm.getNavMode(); 
    String parentID=actionForm.getParentID();
    
    //Add By Jim Zhou       2007/0110       EIP-1292
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    MaintDmsDocumentForm documentForm = (MaintDmsDocumentForm) form;
    Integer documentID = TextUtility.parseIntegerObj(documentForm.getID());
    DmsDocument document = docRetrievalManager.getDocument(documentID);
    DocumentValidateManager docValidateManager = new DocumentValidateManager(sessionContainer, conn);
    StringBuffer message = new StringBuffer();

    DmsValidation validation = docValidateManager.validateOperateAction(document, false, "E");
    List lstIdMisRight = validation.getLstIdReject();
    List lstIdBeLocked = validation.getLstIdlocked();
    List lstIdBeDeleted = validation.getLstIdDeleted();
    List lstIdBeArchived = validation.getLstIdArchived();
    List lstIdRelationship = validation.getLstIdHaveRelationship();
    if (!lstIdMisRight.isEmpty() ||
        !lstIdBeDeleted.isEmpty() ||
        !lstIdBeArchived.isEmpty()){
      for (int i=0; i<lstIdMisRight.size(); i++) {
        this.addError(request,"errors.dms.no_permission",docRetrievalManager.getLocationPath((Integer)lstIdMisRight.get(i)));
      }
      for (int i=0; i<lstIdBeLocked.size(); i++) {
        this.addError(request,"errors.dms.been_checkout",docRetrievalManager.getLocationPath((Integer)lstIdBeLocked.get(i)));
      }
      for (int i=0; i<lstIdBeDeleted.size(); i++) {
        this.addError(request,"errors.dms.been_deleted",docRetrievalManager.getLocationPath((Integer)lstIdBeDeleted.get(i)));
      }
      for (int i=0; i<lstIdBeArchived.size(); i++) {
        this.addError(request,"errors.dms.been_archived",docRetrievalManager.getLocationPath((Integer)lstIdBeArchived.get(i)));
      }
      if (Utility.isEmpty(documentForm.getReturnTo())){
        return mapping.findForward("Home");
      } else {
        ActionForward actionForward = new ActionForward();
        actionForward.setPath("/dms/" + documentForm.getReturnTo());
        return actionForward;
      }
    }
    //Add
 
    if("CONVERT".equals(opMode)){
      try {
        this.convertToCompoundDoc(mapping, form, request, response);
        this.commit(request);
        addMessage(request, MESSAGE_CONVERT_SUCCESS);
      } catch (ApplicationException appEx) {
        this.rollback(request);
        handleApplicationException(request, appEx);
      }
      if (isError(request)) {
        actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
      } else {
        actionForm.setParentID(parentID);
        actionForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
        actionForm.setDocumentType(DmsDocument.COMPOUND_DOC_TYPE);
        request.setAttribute("curFunctionCode",SystemFunctionConstant.DMS_COMPOUND_DOCUMENT);
        return mapping.findForward(DmsOperationConstant.CREATE_COMPOUND_DOCUMENT_VIEW);
      }
    }else if("CONVERT_PAGE".equals(opMode)){
      actionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
      return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
    }else{
      return super.execute(mapping,form,request,response);   
    }
  }
  
  /**
   * Convert the docuemnt or paper document to compound document .
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void convertToCompoundDoc(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
    InputStream inputStream = null;
    FormFile formFile = null;
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager=new DocumentRetrievalManager(sessionContainer,conn);
    DmsDocumentDAObject dmsDocumentDAO=new DmsDocumentDAObject(sessionContainer,conn);
    DocumentValidateManager docValidateManager=new DocumentValidateManager(sessionContainer,conn);
    DmsContentDAObject dmsContentDAO=new DmsContentDAObject(sessionContainer,conn);
    DmsContentManager dmsContentManager = new DmsContentManager(sessionContainer, conn);
    
    MaintDmsDocumentForm actionForm=(MaintDmsDocumentForm)form;
    DmsDocument newDocument=new DmsDocument();
    DmsDocumentNameConvertor documentNameConvertor=null;
    DmsContentStoreHandler contentStoreHandler = null;
    if(!Utility.isEmpty(actionForm.getID())){
      Integer ID=TextUtility.parseIntegerObj(actionForm.getID());
      DmsDocument dmsDocument=docRetrievalManager.getDocument(ID);
      if(DmsDocument.DOCUMENT_TYPE.equals(dmsDocument.getDocumentType())){  
        dmsDocument.setDocumentType(DmsDocument.COMPOUND_DOC_TYPE);
        newDocument=(DmsDocument)dmsDocumentDAO.updateObject(dmsDocument);
      }else if(DmsDocument.PAPER_DOC_TYPE.equals(dmsDocument.getDocumentType())){
        try {
          formFile = actionForm.getUploadFile();
          if (formFile !=null) {
            inputStream = formFile.getInputStream();
          }
        } catch (Exception ee) {
          log.error(ee, ee);
        }
        dmsDocument.setDocumentType(DmsDocument.COMPOUND_DOC_TYPE);
        String sExt = null;
        if(dmsDocument.getDocumentName().indexOf(".")<0 && formFile.getFileName().indexOf(".")>0){
          String fileName=formFile.getFileName();
          sExt = fileName.substring(fileName.lastIndexOf("."),fileName.length());
          dmsDocument.setDocumentName(dmsDocument.getDocumentName()+sExt); 
        }
        dmsDocument.setItemSize(new Integer(formFile.getFileSize()));
        newDocument=(DmsDocument)dmsDocumentDAO.updateObject(dmsDocument); 
        docValidateManager.checkStorageLimitAvailable(dmsDocument);
        String foldersDir = docRetrievalManager.getFoldersDirectories(newDocument).toString();
        //Create Physical Document
        log.debug("parent FolderPath = " + foldersDir);
        //Create physical root directory & Content


         DmsVersion dmsVersion = docRetrievalManager.getTopVersionByDocumentID(newDocument.getID());
//        Integer contentID = dmsVersion.getContentID();
//        DmsContent dmsContent=(DmsContent)dmsContentDAO.getObjectByID(contentID);
//        dmsContent.setConvertedName(convertedName);
//        DmsContent newDmsContent=(DmsContent)dmsContentDAO.updateObject(dmsContent);

         
        // create physical file
         
         try {
           documentNameConvertor = (DmsDocumentNameConvertor)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_NAME_CONVERTOR_CLASS)).newInstance();
           //this.documentNameConvertor = (DmsDocumentNameConvertor)Class.forName("com.dcivision.dms.core.ShortDocumentNameConvertor").newInstance();        
         } catch (Exception e) {
           log.error("Name Convertor class not found.", e);
           throw new ApplicationException(DmsErrorConstant.NAME_CONVERTOR_CLASS_NOT_FOUND);
         }
         String convertedName = "";
         //use the shortDocumentNameConvertor
         String  convertClassName=SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_NAME_CONVERTOR_CLASS);
         if(convertClassName.indexOf("ShortDocumentNameConvertor")>0){
           DmsDocument tempDmsDocument = new DmsDocument(); 
           tempDmsDocument.setID(dmsVersion.getContentID());
           convertedName = documentNameConvertor.encryptDocumentName(tempDmsDocument);
         }else{
           convertedName = documentNameConvertor.encryptDocumentName(dmsDocument);
         }
         
        contentStoreHandler = dmsContentManager.writeDmsDocumentStoreContent(newDocument,convertedName,inputStream);
        Integer segmentNoInt = (Integer)contentStoreHandler.getProperty(DmsContentStoreHandler.SEGMENTNUM_PROPERTY);      
        
        
        //lee.lv edit in 06/04/14 for 4849
        Integer contentID = dmsVersion.getContentID();
        DmsContent dmsContent=(DmsContent)dmsContentDAO.getObjectByID(contentID);
        dmsContent.setConvertedName(convertedName);
        dmsContent.setSegmentNO(segmentNoInt);
        dmsContent.setExt(sExt);
        dmsContent.setContentType(URLConnection.guessContentTypeFromName(dmsDocument.getDocumentName()));
        DmsContent newDmsContent=(DmsContent)dmsContentDAO.updateObject(dmsContent);
      
      
      }
      selectChildList(newDocument.getID(),newDocument.getRootID(),request,form);
    }
  }
  
  /**
   * get the list of compound document's sub documents.
   * @param ID
   * @param rootID
   * @param request
   */
  public void selectChildList(Integer ID, Integer rootID,HttpServletRequest request,ActionForm form){
    MaintDmsDocumentForm maintForm=(MaintDmsDocumentForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    int startOffset = TextUtility.parseInteger(maintForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(maintForm.getPageOffset());
    List documentList = null;
    List newDocumentList=new ArrayList();
    try{
       documentList = docRetrievalManager.getDocumentListByParentIDRootID(ID, rootID);
     } catch (Exception ee) {
        log.error(ee,ee);
     }
     if (!Utility.isEmpty(documentList)){
      if(documentList.size()-startOffset>pageSize){
        for(int i=startOffset-1;i<startOffset-1+pageSize;i++){
          DmsDocument dmsDocument=(DmsDocument)documentList.get(i);
          dmsDocument.setRowNum(i+1);
          dmsDocument.setRecordCount(documentList.size());
          //dmsDocument.setHasRelationship(docRetrievalManager.hasRelationship(dmsDocument.getID(),""));
          newDocumentList.add(dmsDocument);
        }
      }else{
        for(int i=startOffset-1;i<documentList.size();i++){
          DmsDocument dmsDocument=(DmsDocument)documentList.get(i);
          dmsDocument.setRowNum(i+1);
          dmsDocument.setRecordCount(documentList.size());
          //dmsDocument.setHasRelationship(docRetrievalManager.hasRelationship(dmsDocument.getID(),""));
          newDocumentList.add(dmsDocument);    
        }
      }
    }

    request.setAttribute("dmsCompoundDocumentList", newDocumentList);

  }

}